//
//  ForumViewController.m
//  cityCar
//
//  Created by yao on 14-11-3.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ForumViewController.h"
#import "CCSegmentedControl.h"
#import "ForumView.h"
#import "ForumCollectionCell.h"
#import "ForumCarCollectionCell.h"
#import "ForumDetailViewController.h"
#import "SearchViewController.h"
#import "CKWabViewController.h"
#import "PullCollectionViewCell.h"
#import "ForumContentViewController.h"
#import "Forum.h"

@interface ForumViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, retain)UICollectionView *collection;
@property(nonatomic, retain)UIView *headView;
// 存入本地用于显示最近访问的数组
@property(nonatomic, retain)NSMutableArray *recentlyArray;
@end

@implementation ForumViewController

- (void)dealloc
{
    [_collection release];
    [_headView release];
    [_recentlyArray release];
    // 移除通知中心
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.recentlyArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupViews];
}

- (void)setupViews
{
    // 设置标题
    self.title = @"论坛";
    
    // 背景色
    self.view.backgroundColor = [WebColor white];
    
    // 视图控制器的宽度
    CGFloat x = self.view.frame.size.width;
    // 创建一个空白View在顶部
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, x, 35)];
    [self.view addSubview:self.headView];
    [_headView release];
    
    NSArray *arrName = @[@"热门", @"车系", @"地区", @"综合"];
    
    
    for (int i = 0; i < 4; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(5 + x / 4 * i, 5, x / 4 - 10, self.headView.frame.size.height - 10);
        [button setTitle:arrName[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        button.tintColor = [WebColor dimGray];
        button.layer.cornerRadius = 10;
        [self.headView addSubview:button];
        button.tag = 10000 + i;
        if (i == 0) {
            button.tintColor = [WebColor white];
            button.backgroundColor = [WebColor darkGray];
        }
    }
    
    // collectionView布局
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 64 - 35 - 49);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 0;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64 + 35, self.view.frame.size.width, self.view.frame.size.height - 64 - 35 - 49) collectionViewLayout:flowLayout];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.backgroundColor = [WebColor white];
    self.collection.showsHorizontalScrollIndicator = NO;
    self.collection.pagingEnabled = YES;
    
    //注册Cell
    [self.collection registerClass:[ForumCollectionCell class] forCellWithReuseIdentifier:@"forum"];
    [self.collection registerClass:[ForumCarCollectionCell class] forCellWithReuseIdentifier:@"forumCar"];
    [self.collection registerClass:[ForumCarCollectionCell class] forCellWithReuseIdentifier:@"forumArea"];
    [self.collection registerClass:[ForumCarCollectionCell class] forCellWithReuseIdentifier:@"forumz"];
    [self.collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self.view addSubview:self.collection];
    [_collection release];
    
}

// 点击热门，车系，地区，综合的方法
- (void)buttonClicked:(UIButton *)button
{
    
    for (UIButton *but in [self.headView subviews]) {
        but.tintColor = [WebColor dimGray];
        but.backgroundColor = [WebColor white];
    }
    button.tintColor = [WebColor white];
    button.backgroundColor = [WebColor darkGray];
    
    switch (button.tag) {
        case 10000:
            self.collection.contentOffset = CGPointMake(0, 0);
            break;
        case 10001:
            self.collection.contentOffset = CGPointMake(320, 0);
            break;
        case 10002:
            self.collection.contentOffset = CGPointMake(320 * 2, 0);
            break;
        case 10003:
            self.collection.contentOffset = CGPointMake(320 * 3, 0);
            break;
        default:
            break;
    }
    
}

// 通过改变偏移量而改变button的背景色
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int number = scrollView.contentOffset.x / scrollView.frame.size.width;
    
    UIButton *button1 = (UIButton *)[self.view viewWithTag:10000];
    UIButton *button2 = (UIButton *)[self.view viewWithTag:10001];
    UIButton *button3 = (UIButton *)[self.view viewWithTag:10002];
    UIButton *button4 = (UIButton *)[self.view viewWithTag:10003];
    
    NSArray *arr = @[button1, button2, button3, button4];
    for (int i = 0; i < arr.count; i++) {
        UIButton *button = [arr objectAtIndex:i];
        if (button.tag == 10000 + number) {
            button.backgroundColor = [WebColor darkGray];
            button.tintColor = [WebColor white];
        } else {
            button.backgroundColor = [WebColor white];
            button.tintColor = [WebColor dimGray];
        }
    }
    
}

#pragma mark - collectionView协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 4;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            ForumCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"forum" forIndexPath:indexPath];
            void (^blockValue)(Forum *str) = ^(Forum *str){
                
                ForumContentViewController *forumContentVC = [[ForumContentViewController alloc] init];
                forumContentVC.forum = str;
                [self presentViewController:forumContentVC animated:YES completion:^{
                }];
                
            };
            cell.forumView.block = blockValue;
            return cell;
        }
            break;
        case 1:
        {
            ForumCarCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"forumCar" forIndexPath:indexPath];
            void(^block)(NSString *, NSString *) = ^(NSString *Id, NSString *name){
                ForumDetailViewController *forumVC = [[ForumDetailViewController alloc] init];
                forumVC.string = Id;
                forumVC.dic = @{@"Name": name};
                
                // 创建forumGather对象，存到recentlyArray数组中，并存入本地，显示在最近访问中。
                ForumGather *forum = [[ForumGather alloc] init];
                forum.Id = Id;
                forum.name = name;
                
                // 存本地之前先从本地读取
                static int temp = 1;
                if (temp == 1) {
                    NSArray *achieveArray = [self achieveDate];
                    if (achieveArray.count != 0) {
                        [self.recentlyArray addObjectsFromArray:achieveArray];
                    }
                    temp = 0;
                }
                
                // 判断数组里有没有重复的，保证数组中都是不重复的。
                int flag = 1;
                for (ForumGather *fo in self.recentlyArray) {
                    NSString *Id = [NSString stringWithFormat:@"%@", forum.Id];
                    NSString *foId = [NSString stringWithFormat:@"%@", fo.Id];
                    if ([Id isEqualToString:foId]) {
                        
                        flag = 0;
                    }
                }
                if (flag == 1) {
                    [self.recentlyArray addObject:forum];
                }
                
                // 写入本地
                [self locationStore];
                
                [self presentViewController:forumVC animated:YES completion:^{
                    
                }];
                [forumVC release];
            };
            cell.carKind.block = block;
            cell.temp = 1;
            return cell;
        }
            break;
        case 2:
        {
            ForumCarCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"forumArea" forIndexPath:indexPath];
            void(^block)(NSString *, NSString *) = ^(NSString *Id, NSString *name){
                ForumDetailViewController *forumVC = [[ForumDetailViewController alloc] init];
                forumVC.string = Id;
                forumVC.dic = @{@"Name": name};
                
                // 创建forumGather对象，存到recentlyArray数组中，并存入本地，显示在最近访问中。
                ForumGather *forum = [[ForumGather alloc] init];
                forum.Id = Id;
                forum.name = name;
                
                // 存本地之前先从本地读取
                static int temp = 1;
                if (temp == 1) {
                    NSArray *achieveArray = [self achieveDate];
                    if (achieveArray.count != 0) {
                        [self.recentlyArray addObjectsFromArray:achieveArray];
                    }
                    temp = 0;
                }
                
                // 判断数组里有没有重复的，保证数组中都是不重复的。
                int flag = 1;
                for (ForumGather *fo in self.recentlyArray) {
                    NSString *Id = [NSString stringWithFormat:@"%@", forum.Id];
                    NSString *foId = [NSString stringWithFormat:@"%@", fo.Id];
                    if ([Id isEqualToString:foId]) {
                        
                        flag = 0;
                    }
                }
                if (flag == 1) {
                    [self.recentlyArray addObject:forum];
                }
                
                // 写入本地
                [self locationStore];
                
                [self presentViewController:forumVC animated:YES completion:^{
                    
                }];
                [forumVC release];
            };
            cell.carKind.block = block;
            cell.temp = 2;
            return cell;
        }
            break;
            
        default:
        {
            ForumCarCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"forumz" forIndexPath:indexPath];
            void(^block)(NSString *, NSString *) = ^(NSString *Id, NSString *name){
                ForumDetailViewController *forumVC = [[ForumDetailViewController alloc] init];
                forumVC.string = Id;
                forumVC.dic = @{@"Name": name};
                
                // 创建forumGather对象，存到recentlyArray数组中，并存入本地，显示在最近访问中。
                ForumGather *forum = [[ForumGather alloc] init];
                forum.Id = Id;
                forum.name = name;
                
                // 存本地之前先从本地读取
                static int temp = 1;
                if (temp == 1) {
                    NSArray *achieveArray = [self achieveDate];
                    if (achieveArray.count != 0) {
                        [self.recentlyArray addObjectsFromArray:achieveArray];
                    }
                    temp = 0;
                }
                
                // 判断数组里有没有重复的，保证数组中都是不重复的。
                int flag = 1;
                for (ForumGather *fo in self.recentlyArray) {
                    NSString *Id = [NSString stringWithFormat:@"%@", forum.Id];
                    NSString *foId = [NSString stringWithFormat:@"%@", fo.Id];
                    if ([Id isEqualToString:foId]) {
                        
                        flag = 0;
                    }
                }
                if (flag == 1) {
                    [self.recentlyArray addObject:forum];
                }
                
                // 写入本地
                [self locationStore];
                
                [self presentViewController:forumVC animated:YES completion:^{
                    
                }];
                [forumVC release];
            };
            cell.carKind.block = block;
            cell.temp = 3;
            return cell;
        }
            break;
    }
    
}

// 存本地之前先从本地读取
- (NSArray *)achieveDate
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths lastObject];
    NSArray *achieveArray = [NSArray array];
    NSString *carPath = [documentPath stringByAppendingPathComponent:@"recently.aaa"];
    achieveArray = [NSKeyedUnarchiver unarchiveObjectWithFile:carPath];
    
    return achieveArray;
    
}


// 本地存储
- (void)locationStore
{
    // 找到沙盒的路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    // 获取documents的路径
    NSString *documentPath = [paths objectAtIndex:0];
    
    // 归档类，将一个实现了NSCoding协议的对象，写入本地
    NSString *carPath = [documentPath stringByAppendingPathComponent:@"recently.aaa"];
    
    // 如果recently数组大于4删掉多余的
    if (self.recentlyArray.count > 4) {
        for (int i = 0; i < self.recentlyArray.count - 4 + i; i++) {
            [self.recentlyArray removeObjectAtIndex:0];
        }
    }
    
    BOOL carResult = [NSKeyedArchiver archiveRootObject:self.recentlyArray toFile:carPath];
    NSLog(@"最近访问写入本地：%d", carResult);
    
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
